import { app, shell, BrowserWindow, ipcMain,session } from 'electron'
import { join, resolve } from 'path' //  basename, resolve
//normalize，protocol
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset'
import fs from 'fs'
import unzip from 'node-unzip-2'
import Store from 'electron-store'
import os from 'os'
const store = new Store();
// import axios from 'axios'
// import { exec } from 'child_process'
// import express from  'express';
// import { createProxyMiddleware } from 'http-proxy-middleware'

// 创建代理服务器
// const createProxyServer = () => {
//   const app = express();
//   let port:any = 4000;
//   app.use('/activity', createProxyMiddleware({
//     target: 'https://baijiahao.baidu.com/activity',
//     changeOrigin: true,
//     secure: true,
//     pathRewrite: {
//       '^/activity': ''
//     }
//   }));

//   app.use('/pcui', createProxyMiddleware({
//     target: 'https://baijiahao.baidu.com/pcui',
//     changeOrigin: true,
//     secure: true,
//     pathRewrite: {
//       '^/pcui': ''
//     }
//   }));
//   app.listen(port,'192.168.1.15', () => {
//     console.log('Proxy server is running on http://localhost:4000');
//   });
// };
const unique_random_path  = `persist:session-${new Date().getTime()}`  // 每个窗口指定不同的partition
// 获取mac地址
function getMacAddress() {
  const networkInterfaces:any = os.networkInterfaces();
  for (const name of Object.keys(networkInterfaces)) {
      const iface = networkInterfaces[name].find(details => details.family === 'IPv4' && !details.internal);
      if (iface) {
          return iface.mac;
      }
  }
  return null;
}
function createWindow(): void {
  // Create the browser window.
  const mainWindow:any = new BrowserWindow({
    width: 1000,
    height: 670,
    show: false,
    autoHideMenuBar: true, // 隐藏顶部工具栏
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false,
      webSecurity: false,
      partition: unique_random_path, // 为每个窗口指定不同的partition,可以确保每个窗口的cookie和缓存互不影响
       //支持完整node
       nodeIntegration:true,
       contextIsolation:false
    }
  })

  // //只打开一个窗口
  // const gotTheLock = app.requestSingleInstanceLock()
  // if (!gotTheLock) {
  //   app.quit()
  // } else {
  //   app.on('second-instance', () => {
  //     if (mainWindow) {
  //       mainWindow.show();
  //       if (mainWindow.isMinimized()) mainWindow.restore()
  //       mainWindow.focus()
  //     }
  //   });
  // }

    // 主进程中的 IPC 处理逻辑 -- 获取mac地址
    ipcMain.handle('mac-address', async () => {
      try {
        const macAddress = getMacAddress();
        return { success: true, data: macAddress };
      } catch (error:any) {
        return { success: false, message: `获取 mac地址 失败: ${error.message}` };
      }
    });
    // 主进程中的 IPC 处理逻辑 -- 设置指定域名的cookie
    ipcMain.handle('set-cookie', async (_, cookie) => {
      try {
        // await session.defaultSession.cookies.set(cookie);
        await session.fromPartition(unique_random_path).cookies.set(cookie);
        return { success: true, message: 'Cookie 设置成功' };
      } catch (error:any) {
        return { success: false, message: `设置 Cookie 失败: ${error.message}` };
      }
    });

    // 注册删除所有 Cookie 的处理程序
    ipcMain.handle('clear-all-cookies', async () => {
      try {
        // 获取所有 Cookie
        const cookies:any = await session.fromPartition(unique_random_path).cookies.get({});
        // 删除每个 Cookie
        for (const cookie of cookies) {
          await session.fromPartition(unique_random_path).cookies.remove(cookie.value, cookie.name);
        }
        return { success: true, message: '所有 Cookie 已清除',data: cookies };
      } catch (error:any) {
        return { success: false, message: `清除 Cookie 失败: ${error.message}` };
      }
    });

      // 假设这是你的指定目录
  const specifiedDirectory = join(app.getAppPath(), '../renderer/static'); // join(__dirname, 'downloads')
  // 当目录不存在，创建目录
  if (!fs.existsSync(specifiedDirectory)) {
    fs.mkdir(specifiedDirectory, { recursive: true }, (err) => {
      if (err) {
        console.error('Error creating directory:', err);
      } else {
        console.log('Directory created successfully');
      }
    });// 使用recursive选项可以创建嵌套目录
  }
  let downloadItemState:any = {}
  let arr:any = []
  let isExecuting:any = false
  // 主进程中的 IPC 处理逻辑 -- 下载到本地并解压zip文件
  ipcMain.handle('download-file-request', async (_, url) => {
    try {
      return new Promise((resolves, reject) => {
        let index2 = url.lastIndexOf('/'); // 找到最后一个点号的位置
        let index3 = url.lastIndexOf('.')
        let filePath = url.substring(index2+1, index3); // 从开始到点号位置截取字符串
        console.log(filePath)
        let filePaths = resolve(specifiedDirectory ,filePath)
        // resolves({ success: true, message: `已下载文件`, status: 2,data: filePaths })
        if (fs.existsSync(filePaths)) {
          // 文件存在，可以进行操作
          // console.log('File exists.');
          resolves(JSON.stringify({ success: true, message: `已下载文件`, status: 2 }))
        } else {
          arr.push(filePath)
          arr = arr.filter((item, index) => arr.indexOf(item) === index);
          const executeNext2 = (index) => {
            if(index >= arr.length) {
              console.log('end')
              return
            }
            const currentItem = arr[index];
             // 设置超时时间（例如 60 秒）
            // const timeout = 180000; // 60 秒
            let timer;
            const timeout2 = 180000
            let flag_arr:any = []
            console.log(arr, downloadItemState, currentItem)
            // 判断是否为正在进行中、未下载的继续执行下载
            if(downloadItemState && downloadItemState.path == currentItem && downloadItemState.offset < downloadItemState.length) {
              // 恢复之前的下载
              let sessionDownload:any = session.fromPartition(unique_random_path)
              sessionDownload.createInterruptedDownload({
                path: downloadItemState.path,
                urlChain: downloadItemState.url,
                offset: downloadItemState.offset,
                length: downloadItemState.length,
                lastModified: downloadItemState.lastModified,
                eTag: downloadItemState.eTag,
                startTime: downloadItemState.startTime,
              });
            } else {
              mainWindow.webContents.downloadURL(url)
            }
            //监听下载动作
            mainWindow.webContents.session.once('will-download', (_, item:any, __) => {
              // console.log(webContents.id, mainWindow.webContents.id)
              isExecuting = true
              //解压目标目录
              let index = item.getFilename().lastIndexOf('.'); // 找到最后一个点号的位置
              let beforeDot = item.getFilename().substring(0, index); // 从开始到点号位置截取字符串
              // 保存下载项的状态
              downloadItemState = {
                url: item.getURLChain() , // item.getURL(),
                path: beforeDot,
                offset: 0,
                length: item.getTotalBytes(),
                lastModified: item.getLastModifiedTime(),
                eTag: item.getETag(),
                startTime: item.getStartTime(),
              };
              //拼接要存储的路径
              var zipFile = resolve(specifiedDirectory, item.getFilename()) //join(specifiedDirectory, item.getFilename()) // join(app.getAppPath('downloads'), 'static', item.getFilename()) //resolve(__dirname, item.getFilename())
              // console.log(zipFile, beforeDot) // app.getAppPath('downloads')
              // // 设置自动解压
              // item.setAutoUnzip(true);
              console.log('zipFile',item.getFilename(), zipFile)

              // 设置存储路径 否则会弹出对话框
              item.setSavePath(zipFile)

              // event.preventDefault() // 阻止弹窗
              //监听下载过程
              item.on('updated', (_, state) => {
              //   //下载意外中断，可以恢复
                if (state === 'interrupted') {
              //     console.log('Download is interrupted but can be resumed')
                  // if(item.canResume()) {
                  //    item.resume(); // 恢复下载
                  // }
                  resolves(JSON.stringify({ success: true, message: `下载中断`, status: 4 }))
                  // reject({ success: false, message: `下载文件失败1`, status: 0 })
                } else if (state === 'progressing') {
                  //下载正在进行中
                  if (item.isPaused()) { // 下载是否暂停
                      console.log('Download is paused')
                      resolves(JSON.stringify({ success: true, message: `下载停止`, status: 3 }))
                  } else {
                    // 下载进行中
                    console.log(`complete:${(item.getReceivedBytes() / item.getTotalBytes() * 100).toFixed(2)}%`,item.getReceivedBytes())
                    downloadItemState.offset = item.getReceivedBytes();
                    // let progressTimestamp = new Date().getTime();
                    // 任务栏进度条 -1不展示
                    mainWindow.setProgressBar(item.getReceivedBytes() / item.getTotalBytes())
                    let process = `${Math.round((item.getReceivedBytes() / item.getTotalBytes()) * 100)}%`
                    // 把百分比发给渲染进程进行展示
                    mainWindow.webContents.send('updateProgressing', {type:"progress",process, path: currentItem});
                  }
                }
              })

              //监听完成
              item.once('done', (_, state) => {
                console.log(state)
                clearTimeout(timer); // 如果下载正在进行，清除超时定时器
                if (state === 'completed') {
                  var zipTargetPath = resolve(specifiedDirectory,beforeDot)
                  //解压文件路径
                  var zipFile = resolve(specifiedDirectory,item.getFilename())
                  // console.log('解压目标目录',zipTargetPath)
                  // console.log('解压文件路径',zipFile)
                  fs.createReadStream(zipFile).pipe(unzip.Extract({ path: zipTargetPath })).on('close', () => {
                    console.log('Unzipped successfully');
                    // 把百分比发给渲染进程进行展示
                    let process = `${Math.round((item.getReceivedBytes() / item.getTotalBytes()) * 100)}%`
                    flag_arr.push(process)
                    mainWindow.webContents.send('updateProgressing', {type:state,process, path: currentItem});
                  });  //解压时直接会覆盖重名文件
                  // mainWindow.webContents.session.removeListener('will-download', (__, item:any, ___) => {
                  //     console.log(item,'移除监听器')
                  // });
                  // 删除索引为 index 的元素
                  arr = arr.filter((items:any) => items !== beforeDot);
                  setTimeout(() => {
                    executeNext2(0)  
                  }, 1000)
                  downloadItemState = {}
                  isExecuting = false
                  resolves(JSON.stringify({ success: true, message: `下载文件成功`, status: 1 }))
                }else if (state === 'cancelled') {
                  // if(item.canResume()) {
                  //   item.resume(); // 恢复下载
                  // }
                  resolves(JSON.stringify({ success: true, message: `下载取消`, status: 3 }))
                  downloadItemState = {}
                  isExecuting = false
                } else {
                  console.log(`Download failed: ${state}`)
                  reject({ success: false, message: `下载文件失败`, status: 0 })
                }
              })

              // 设置超时逻辑
              timer = setTimeout(() => {
                console.log('Download timed out',);
                // && flag_arr.length > 10 && flag_arr[flag_arr.length - 1] == flag_arr[flag_arr.length - 2]
                if(item.getReceivedBytes() < item.getTotalBytes() && downloadItemState.path == currentItem) {
                  console.log('下载取消');
                  item.cancel(); // 超时后取消下载
                  downloadItemState = {}
                }
              }, timeout2);
            })
          }
          if(!isExecuting) {
            executeNext2(0)  
          }
        }
      })
    } catch (error:any) {
      return { success: false, message: `下载文件失败: ${error.message}` };
    }
  });
  let arr2:any = []
  let downloadItem2:any = {}; // 用于存储当前下载项
  let flag = 1;
  let lastUpdateTime:any = '';
  // 主进程中的 IPC 处理逻辑 -- 下载到本地并解压zip文件
  ipcMain.handle('download-file-request2', async (_, url) => {
    try {
      const { download } = await import('electron-dl');
      return new Promise((resolves, reject) => {
        let index2 = url.lastIndexOf('/'); // 找到最后一个点号的位置
        let index3 = url.lastIndexOf('.')
        let filePath = url.substring(index2+1, index3); // 从开始到点号位置截取字符串
        console.log(filePath)
        let filePaths = resolve(specifiedDirectory ,filePath)
        if (fs.existsSync(filePaths)) {
          // 文件存在，可以进行操作
          resolves(JSON.stringify({ success: true, message: `已下载文件`, status: 2 }))
        } else {
          // 设置超时时间（例如 60 秒）
          // const timeout = 180000; // 60 秒
          const timeout2 = 120000
          let index4 = url.lastIndexOf('/'); // 找到最后一个点号的位置
          let filePath2 = url.substring(index4+1); // 从开始到点号位置截取字符串
          arr2.push({url: url, directory: filePath2, path: filePath})
          arr2 = arr2.reduce((acc, current) => {
            if (!acc.some(item => item.path === current.path)) {
              acc.push(current);
            }
            return acc;
          }, []);
          const executeNext2 = async (index) => {
            if(index >= arr2.length) {
              console.log('end')
              return
            }
            const currentItem = arr2[index];
            console.log(arr2,'arr2')
            console.log('downloadItem2',downloadItem2)
            // const dl = await download(mainWindow, currentItem.url, {
            //   saveAs: false,
            //   directory: resolve(specifiedDirectory)
            // });
            //  // 监听进度事件
            // dl.on('progress', (progress) => {
            //   console.log('download-progress', progress);
            // });
            // dl.on('updated', (event:any) => {
            //   if (event.state === 'interrupted') {
            //     console.log('Download is interrupted but can be resumed');
            //     // 处理中断逻辑，例如重试下载或提示用户
            //   } else if (event.state === 'progressing') {
            //     if (dl.isPaused()) {
            //       console.log('Download is paused');
            //     } else {
            //       console.log(`Download progress: ${(dl.getReceivedBytes() / dl.getTotalBytes() * 100).toFixed(2)}%`);
            //     }
            //   }
            // });
          
            // dl.once('done', (error, filePath) => {
            //   if (error) {
            //     console.error('Download failed:', error);
            //   } else {
            //     console.log('Download completed:', filePath);
            //   }
            // });
            let options:any = {
              saveAs: false,
              directory: resolve(specifiedDirectory),   //拼接要存储的路径
              filename: currentItem.directory,
              timeout: 180000,
              resume: true, // 启用断点续传
              startOffset: downloadItem2.startBytes || 0, // 从1024字节开始下载
              headers: downloadItem2.startBytes > 0 ? { 'Range': `bytes=${downloadItem2.startBytes}-` } : '',
              onStarted: (item) => {
                lastUpdateTime = Date.now();
                console.log('Download started',item.getState(),item.getFilename(),lastUpdateTime);
                if(downloadItem2.startBytes > 0) {
                  flag = 2
                }
              },
              onCancel: () => {},
              onProgress: (progress) => {
                  downloadItem2 = {
                    saveAs: false,
                    directory: resolve(specifiedDirectory),   //拼接要存储的路径
                    filename: currentItem.directory,
                    timeout: 180000,
                    autoResume: true, // 启用断点续传
                    startBytes: progress.transferredBytes, // 从1024字节开始下载
                  }
                  console.log(`${Math.round((progress.transferredBytes / progress.totalBytes) * 100)}%`, flag); // 监听进度
                  // 任务栏进度条 -1不展示
                  mainWindow.setProgressBar(progress.transferredBytes / progress.totalBytes)
                  let process = `${Math.round((progress.transferredBytes / progress.totalBytes) * 100)}%`
                  // 把百分比发给渲染进程进行展示
                  if(process == '100%') {
                    mainWindow.webContents.send('updateProgressing2', {type:"completed",process, path: currentItem.path, flag: flag});
                  } else {
                    mainWindow.webContents.send('updateProgressing2', {type:"progress",process, path: currentItem.path, flag: flag});
                    const currentTime = Date.now();
                    if(currentTime - lastUpdateTime > 120000) {
                      // 设置超时逻辑
                      setTimeout(() => {
                        console.log('Download timed out1');
                        if(progress.transferredBytes < progress.totalBytes && downloadItem2.filename == currentItem.directory) {
                          console.log('下载取消');
                          // 删除索引为 index 的元素
                          arr2 = arr2.filter((items:any) => items.path !== currentItem.path);
                          downloadItem2 = {}
                          resolves(JSON.stringify({ success: true, message: `下载超时`, status: 3 }))
                        }
                      }, timeout2);
                    }
                  }
              },
              // onCompleted: (err, file) => {
              //     if (err) {
              //         console.error('Download failed:', err);
              //     } else {
              //         console.log('Download finished:', file.path);
              //     }
              // }
            };
            download(mainWindow, currentItem.url, options).then((dl:any) => {
              console.log('completed:',dl.getSavePath());
              //解压目标目录
              let index = currentItem.directory.lastIndexOf('.'); // 找到最后一个点号的位置
              let beforeDot = currentItem.directory.substring(0, index); // 从开始到点号位置截取字符串
              var zipTargetPath = resolve(specifiedDirectory,beforeDot)
              //解压文件路径
              var zipFile = resolve(specifiedDirectory,currentItem.directory)
              // console.log('解压目标目录',zipTargetPath)
              // console.log('解压文件路径',zipFile)
              fs.createReadStream(zipFile).pipe(unzip.Extract({ path: zipTargetPath })).on('close', () => {
                console.log('Unzipped successfully');
                // 删除索引为 index 的元素
                arr2 = arr2.filter((items:any) => items.path !== currentItem.path);
                downloadItem2 = {}
                flag = 1
                resolves(JSON.stringify({ success: true, message: `解压成功`, status: 1 }))
              });  //解压时直接会覆盖重名文件
              setTimeout(() => {
                executeNext2(index+1)  
              }, 1000)
            }).catch(err => {
              console.error('err:', err);
              reject({ success: false, message: `下载文件失败`, status: 0 })
            });
          }
          executeNext2(0)
        }
      })
    } catch (error:any) {
      return { success: false, message: `下载文件失败: ${error.message}` };
    }
  })

 // 读取文件-- 是否有解压后的文件
  ipcMain.handle('list-directory', async(_, dirPath) => {
    try {
      let filePaths = join(specifiedDirectory ,dirPath)
      if (fs.existsSync(filePaths)) {
        // 文件存在，可以进行操作
        console.log('File exists.list-directory');
        const results = await new Promise((resolves, reject) => {
          fs.readdir(filePaths, async (err, data) => {
            if (err) {
              console.error(err);
              reject(err)
            }
            let index = dirPath.lastIndexOf('_'); // 找到最后一个点号的位置
            let path = dirPath.substring(index+1); // 从开始到点号位置截取字符串
            resolves({ imageArr: data, path:path })
          })
        })
        // let arr = fs.readdirSync(filePaths);  // 读取该路径下所有文件
        return results
      } else {
        return []
      }
    }catch (error){
        return 0
    }
  })

  // 获取文件--解压后的图片文件
  ipcMain.handle('read-file', async(_, filePath) => {
      let filePaths = join(specifiedDirectory ,filePath)
      if (fs.existsSync(filePaths)) {
        // 文件存在，可以进行操作
        console.log('File exists.read-file');
        const results:any = [];
        return new Promise((resolves, rejects) => {
          fs.readdir(filePaths, async(err, data) => {
            if (err) {
              console.error(err);
              rejects(err)
            }
            console.log('read-file',data)
            for(let i in data) {
              const result = await new Promise((resolve, reject) => {
                fs.readFile(join(filePaths, data[i]), (err, res) => {
                  if (err) {
                    console.error(err);
                    reject(err)
                  }
                  let index = data[i].lastIndexOf('.'); // 找到最后一个点号的位置
                  let beforeDot = data[i].substring(index+1); // 从开始到点号位置截取字符串
                  // 将 Buffer 转换为 Blob，并通过 IPC 发送给渲染进程
                  // const blob = new Blob([data], { type: `image/${beforeDot}`}); // 根据文件类型调整 MIME 类型
                  let picPath = join(filePaths, data[i])
                  // let file =  new File([data],picPath,{type:'image/'+beforeDot})
                  // console.log(blob)
                  resolve({data: res, type: `image/${beforeDot}`,picPath: picPath, name: data[i]})
                });
              })
              results.push(result)
            }
            resolves(results)
          })// 读取该路径下所有文件
        })
      } else {
        console.error('File not found.');
        return 'File not found.'
      }

      // fs.stat(filePaths, (err, stats) => {
      //   if (err) {
      //     console.error('Error checking file:', err);
      //     return;
      //   }

      //   if (stats.isDirectory()) {
      //     console.error('Error: The provided path is a directory, not a file.');
      //   } else if (stats.isFile()) {
      //     console.log('465645645656456');

      //   } else {
      //     console.error('Error: The provided path is neither a file nor a directory.');
      //   }
      // });

  })

  // 读取文件-- 是否有json文件并读取json文件
  ipcMain.handle('json-directory', async(_, dirPath) => {
    try {
      let filePaths = join(specifiedDirectory ,dirPath)
      if (fs.existsSync(filePaths)) {
        // 文件存在，可以进行操作
        console.log('File exists.json-directory');
        const results = await new Promise((resolves, reject) => {
          fs.readFile(filePaths, 'utf-8',(err, data) => {
            if (err) {
              reject(err)
            }
            let index = dirPath.lastIndexOf('_'); // 找到最后一个点号的位置
            let index2 = dirPath.lastIndexOf('.'); // 找到最后一个点号的位置
            let path = dirPath.substring(index+1, index2); // 从开始到点号位置截取字符串
            resolves({ urlArr: data, article_id:path, type:2 })
          });
        })
        // let arr = fs.readdirSync(filePaths);  // 读取该路径下所有文件
        return results
      } else {
        return { type:1 }
      }
    }catch (error){
      return { type:0, message:error }
    }
  })
  // 监听渲染进程的请求-- 图片上传后创建json文件
  ipcMain.handle('create-file', async (_, filePath, data) => {
    try {
      const filePaths = join(specifiedDirectory, filePath);
      const result = await new Promise((resolve, reject) => {
        fs.writeFile(filePaths, JSON.stringify(data, null, 2), (err) => {
          if (err) {
            reject ({ success: false, message: err })
          }
          resolve ({ success: true, message: '文件创建成功' })
        });
      })
      return result
    } catch (error:any) {
      return { success: false, message: error.message };
    }
  });
  // 监听渲染进程的请求-- 读取json文件
  ipcMain.handle('read-json-file', async (_, filePath) => {
    try {
      const filePaths = join(specifiedDirectory, filePath);
      const res = await new Promise((resolve, reject) => {
        fs.readFile(filePaths, 'utf-8',(err, data) => {
          if (err) {
            reject(err)
          }
          let index = filePath.lastIndexOf('.'); // 找到最后一个点号的位置
          let idx = filePath.lastIndexOf('_')
          let beforeDot = filePath.substring(idx+1, index); // 从开始到点号位置截取字符串
          console.log(beforeDot)
          resolve({success: true,data: data,id: beforeDot})
        });
      });
      return res
    } catch (error:any) {
      return { success: false, message: error.message };
    }
  });

  // 注册删除文件的处理程序--删除文件
  ipcMain.handle('delete-file', async (_, filePath:any) => {
      try {
        // 确保路径是绝对路径
        const absolutePath = join(specifiedDirectory, filePath);
        // 删除文件
        // fs.unlinkSync(absolutePath);
        if (fs.existsSync(absolutePath)) {
          // 文件存在，可以进行操作
          console.log('File exists.delete-file');
          // fs.unlink unlinkSync删除文件操作，不可以删除文件夹
          // fs.rmdir && fs.rmdirSync 进行删除文件夹操作，但文件夹必须为空文件夹
          const res = await new Promise((resolves, rejects) => {
            fs.unlink(absolutePath, (err) => {
              if (err) {
                console.error('Error deleting file:', err);
                rejects({ success: false, message: `删除文件失败: ${err}` })
              }
              console.log('File deleted successfully');
              resolves({ success: true, message: '文件删除成功' })
            });
          })
          return res
          // try {
          //   fs.unlinkSync(absolutePath);
          //   console.log('文件已成功删除');
          // } catch (err) {
          //   console.error('删除文件时发生错误:', err);
          // }
        } else {
          return { success: false, message: '文件未找到' }
        }
      } catch (error:any) {
        return { success: false, message: `删除文件失败: ${error.message}` };
      }
  });
  // 注册删除文件的处理程序-- 删除文件夹
  ipcMain.handle('delete-folder', async (_, filePath:any) => {
    try {
      // 确保路径是绝对路径
      const absolutePath = join(specifiedDirectory, filePath);
      if (fs.existsSync(absolutePath)) {
        // 文件存在，可以进行操作
        console.log('File exists.delete-folder');
        // fs.unlink unlinkSync删除文件操作，不可以删除文件夹
        // fs.rmdir && fs.rmdirSync 进行删除文件夹操作，但文件夹必须为空文件夹
        const results:any = [];
        const res = await new Promise((resolves, rejects) => {
          fs.readdir(absolutePath, async (err, data) => {
            if (err) {
              console.error(err);
              rejects(err)
            }
            console.log('rrrrrrrrrrr', data)
            for(let i in data) {
              let filePath = join(absolutePath ,data[i])
              const result = await new Promise((resolve1, reject1) => {
                fs.unlink(filePath, (err) => {
                  if (err) {
                    console.error('Error deleting file2:', err);
                    reject1({ success: false, message: `删除文件失败: ${err}` })
                  }
                  console.log('File deleted successfully2');
                  resolve1({ success: true, message: '文件删除成功' })
                });
              })
              results.push(result)
            }
            console.log('adasdasd', results)
            fs.rmdir(absolutePath, (err) => {
              if (err) {
                console.error('Error deleting file:', err);
                rejects({ success: false, message: `删除文件夹失败: ${err}` })
              }
              console.log('File deleted successfully2');
              resolves(results)
            });
          })
        })
        return { success: true, message: '文件夹删除成功',data: res }
      } else {
        return { success: false, message: '文件夹未找到' }
      }
    } catch (error:any) {
      return { success: false, message: `删除文件夹失败: ${error.message}` };
    }
  })

  //储存用户信息
  ipcMain.handle('set-user-info', (_, userInfo) => {
    try {
      store.set('userInfo', userInfo);
      return { success: true, message: '设置成功' };
    } catch (error:any) {
      return { success: false, message: `设置失败: ${error.message}` };
    }
  });

  ipcMain.handle('get-user-info', () => {
    try {
      return { success: true, message: '获取成功', userInfo:  store.get('userInfo')};
    } catch (error:any) {
      return { success: false, message: `获取失败: ${error.message}` };
    }
  });

  ipcMain.handle('clear-user-info', () => {
    try {
      store.delete('userInfo');
      return { success: true, message: '删除成功' };
    } catch (error:any) {
      return { success: false, message: `删除失败: ${error.message}` };
    }
  });

  // session.defaultSession.setProxy({
  //   proxyRules: 'https://baijiahao.baidu.com/'
  // });
  // session.defaultSession.setProxy({
  //   proxyRules: 'https://www.huaicaikeyu.cn'
  // });
  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })
  // mainWindow.loadURL('https://baijiahao.baidu.com'); // 确保这里的URL与你的Vue开发服务器匹配
  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  console.log(process.env['ELECTRON_RENDERER_URL'])
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    // mainWindow.loadURL(`http://192.168.1.15:5173//${join(__dirname, '../renderer/index.html')}`)
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  // exec('node server.ts', (err,stdout,stderr) => {
  //   if(err) {
  //     console.log(stderr)
  //   }
  //   console.log(stdout)
  // })

  // Set app user model id for windows
  electronApp.setAppUserModelId('com.electron')

  // Default open or close DevTools by F12 in development
  // and ignore CommandOrControl + R in production.
  // see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  // IPC test
  ipcMain.on('ping', () => console.log('pong'))

  createWindow()

  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
  app.commandLine.appendSwitch("disable-site-isolation-trials")
  // let storedCookie = ''; // 用于存储提取的 cookie
  // const loginFilter = { urls: ['https://baijiahao.baidu.com'] };
  // // 监听响应并提取 Set-Cookie
  // session.defaultSession.webRequest.onCompleted(loginFilter, (details:any) => {
  //     const setCookieHeader = details.responseHeaders['Set-Cookie'];
  //     console.log('Stored setCookieHeader:', details);
  //     if (setCookieHeader) {
  //       // 提取 cookie
  //       storedCookie = setCookieHeader.join('; '); // 将多个 cookie 合并为一个字符串
  //       console.log('Stored Cookie:', storedCookie);
  //     }
  // });

  // // 需要设置cookie字段的请求路径
  // const requestsFilter = {
  //   urls: ['https://baijiahao.baidu.com']
  // };
  // // 为需要的请求添加请求头中的cookie字段
  // session.defaultSession.webRequest.onBeforeSendHeaders(requestsFilter, (details, callback) => {
  //   console.log('Request URL:', details); // 打印请求的 URL
  //   if (details.url.startsWith('file://')) {
  //     details.requestHeaders['Origin'] = 'https://baijiahao.baidu.com'; // 设置请求头中的 Origin，以绕过 CORS 检查（仅在开发中推荐）
  //   }
  //   if (!details.url.includes('https://baijiahao.baidu.com')) {
  //     console.log('Request URL:', details.url); // 打印请求的 URL
  //     if (storedCookie) {
  //       details.requestHeaders['Cookie'] = storedCookie; // 使用提取的 cookie
  //       console.log('Modified Headers:', details.requestHeaders); // 打印修改后的请求头
  //     }
  //   }
  //   callback({ requestHeaders: details.requestHeaders })
  // })
  // session.defaultSession.webRequest.onHeadersReceived(requestsFilter, (details, callback) => {
  //   console.log('Request URL:', details); // 打印请求的 URL
  //   if (details.responseHeaders && details.responseHeaders['Set-Cookie']) {
  //     for (let i = 0; i < details.responseHeaders['Set-Cookie'].length; i++) {
  //       details.responseHeaders['Set-Cookie'][i] += ';SameSite=None;Secure';
  //     }
  //   }
  //   callback({ responseHeaders: details.responseHeaders });
  // });
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('ready', () => {
  console.log('ready 程序启动时');
  // createProxyServer(); // 启动代理服务器
  // const { defaultSession } = session;
  // const rawString = `BIDUPSID=9783AE509A6A036AAC8B53CCEB41763C; PSTM=1705024699; MAWEBCUID=web_cZszphDSxGIzOqcQhAhfKyaToGOCRAUixLRqECRcQSKibcurXH; BAIDUID=8A2C4E89670246269AB9ACB328B14E8C:FG=1; theme=bjh; BDUSS_BFESS=V2fmhSVk55ZkNYNWcyOVQyckQtRVVkTmNscHJ4dmwzZWljbG1rVDlUby1OYjFuSUFBQUFBJCQAAAAAAAAAAAEAAAD33pBVTGVlenlvdW5nNjQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD6olWc-qJVnMF; Hm_lvt_f2ee7f5c2284ca4c112e62165bc44c75=1737863134; devStoken=4ca78e763eea87fc365ba6d754f582a9a25b10f89abb03aefe0121fcb1d5b8f9; bjhStoken=0a11458787e6b087d1422798a4f067c3a25b10f89abb03aefe0121fcb1d5b8f9; H_PS_PSSID=60278_61027_61986_62053_62061; H_WISE_SIDS=60278_61027_61986_62053_62061; BA_HECTOR=8k8gah800401ah0k0l848405154v4r1jqderh1v; BAIDUID_BFESS=8A2C4E89670246269AB9ACB328B14E8C:FG=1; BDRCVFR[feWj1Vr5u3D]=I67x6TjHwwYf0; delPer=0; PSINO=2; ZFY=pO2IidVZI9hrSIHGt6f7Q5tMhPVwuN5jPQfrBPKnOrc:C; H_WISE_SIDS_BFESS=60278_61027_61986_62053_62061; log_first_time=1738985331466; log_last_time=1738985331466; BDORZ=B490B5EBF6F3CD402E515D22BCDA1598; Hm_lvt_f7b8c775c6c8b6a716a75df506fb72df=1737800254,1737861184,1738898174,1738992551; Hm_lpvt_f7b8c775c6c8b6a716a75df506fb72df=1738992551; HMACCOUNT=D50073EF615640A1; __bid_n=194de68744998883db3d9f; PHPSESSID=oafn5mrdln6mo1s0o9jjaspeo5; XFI=a0ea0880-e5dd-11ef-a884-27f03b8c27ae; XFCS=630B050ECC1B612E6F77D63A07D69C1074C67A40188F2A929620D8061F99BD6A; XFT=3MMfP3hy5iMLPj/dx0BX5x+LeUVflmgZu+BXK8GBTAM=; ab_sr=1.0.1_ODQ2NDAzMmYxZDY0NTI0NmI2MjU4NGIyNTM0ZmI1ZGZhNThjOTY2MzMxODc1NWQ4MzY2NDM0MTc1YTg2OWU5MzczMGFiOTE4YjQ1OGRhYzNiODIzYTdmMGZkNWE4MmQ5YWMyZDAzNWRlY2ExNmEwZDc5Y2M1OTJlMWFkYzNiMWM1ZDliMTJmZTNkYjI1ZWUxNGY3MGRhOTUyMTY4MDNjMjIwN2I2YWYzNjE0MjRmMDQ3NWVkZGY3M2Y1NDVmYmM2OWM1MDkwM2VjYWNlNzUzZTVmMmE2YmU2MTk4MmQyZTkyMTJmZjJjYjQ5OWM0Y2I4OTM4N2VhMzI5ZDM1NWFjYw==; RT="z=1&dm=baidu.com&si=1f0d8a8c-4904-49fc-930e-2cae47f3829c&ss=m6vr9jmg&sl=j&tt=gs8&bcn=https%3A%2F%2Ffclog.baidu.com%2Flog%2Fweirwood%3Ftype%3Dperf&ld=3eiq&nu=yzenllf&cl=1hu2"`;
  // // const rawString = route.query.cookie
  //   console.log(rawString.split(';'))
  //   let arr = {}
  //   rawString.split(';').reduce((acc:any, item:any) => {
  //     console.log('acc',acc)
  //     const index = item.indexOf('='); // 找到‘=’的位置
  //     const [key, value] = [item.substring(0, index),item.substring(index + 1)]; //item.split('=') 先按'='拆分键和值，然后存储到对象中
  //     arr[key] = encodeURI(value); // 将键值对存储到对象中
  //   }, {});
  //   for(let i in arr) {
  //     console.log(arr[i],i)
  //       // 设置默认会话的cookies
  //     defaultSession.cookies.set({
  //       url: 'https://baijiahao.baidu.com', // 需要设置cookie的URL
  //       name: i.trim(),
  //       value: encodeURI(arr[i]),
  //       path: '/',
  //       httpOnly: false,
  //       sameSite: 'no_restriction',
  //       domain: '.baidu.com' // 注意域名前的点表示这是一个顶级域名
  //     }).then(() => {
  //       console.log('Cookie 设置成功');

  //     })
  //     .catch(error => {
  //       console.error('设置 Cookie 失败:', error);
  //     });
  //   }
  session.defaultSession.cookies.get({ url: 'https://baijiahao.baidu.com' }).then(res=> {
    console.log('Cookie 获取成功', res);
  })
  // protocol.registerFileProtocol('file', (request, callback) => {
  //   const url = request.url.substr('file://'.length);
  //   callback({ path: normalize(`${__dirname}/${url}`) });
  // });
});

// In this file you can include the rest of your app"s specific main process
// code. You can also put them in separate files and require them here.
